package zfbh5

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gogap/logs"
	"go.uber.org/zap"
	"log"
	"strconv"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/confs"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/helper/resphelper/userresp"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/bindlogs"
	"yundian/internel/app/models/fddextsignuser"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/onlinesig"
	"yundian/internel/pkg/utils"
	"yundian/internel/pkg/wechatpay"
	"yundian/internel/pkg/wxpay"
)




// HandleUserLogin 帐号登录
func HandleUserLogin(ctx *gin.Context) {
	param := &request.ZfbUserLoginReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.Ip = ctx.ClientIP()

	var err error
	userInfo := &userresp.PlaceUserInfo{}

	if userInfo, err = logic.NewAuthLogic().ZfbUserLogin(param); err != nil {
		Response(ctx)(err.Error(), CodeError, nil)(OK)
		return
	}

	//pClient, _ := alipaylogic.NewAlipayUserLogic()
	//if err = pClient.XmAlipayLogin(param, userInfo); err != nil {
	//	Response(ctx)(err.Error(), CodeError, nil)(OK)
	//	return
	//}

	Response(ctx)("登录成功", CodeSuccess, userInfo)(OK)
}











var payClient = wxpay.NewPayClient(nil)

// 获取微信登录的openid
func HandleGetWxLoginOpenid(ctx *gin.Context) {
	param := &struct {
		Code  string `form:"code" json:"code" binding:"required"`
		Appid string `form:"appid" json:"appid" binding:"required"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	respData, err := payClient.Login(param.Code, param.Appid, confs.GetSecretByAppid(param.Appid))
	if err != nil {
		zap.L().Error(err.Error())
		Response(ctx)(err.Error(), CodeError, nil)(Error)
		return
	}

	rdbSessionKey := utils.Join(respData.Get("openid"), "-sessionKey-secret") // 保存sessionKey用于解密
	global.Rdb.Set(context.Background(), rdbSessionKey, respData.Get("session_key"), time.Minute*5)
	logs.Info("登录时保存的session key", rdbSessionKey, respData.Get("session_key"))
	Response(ctx)("", CodeSuccess, &struct {
		Openid   string `json:"openid"`
		Unionid  string `json:"unionid"`
		NickName string `json:"nickName"`
	}{
		Openid:   respData.Get("openid"),
		Unionid:  respData.Get("unionid"),
		NickName: respData.Get("nickName"),
	})(OK)
}

// 绑定日志
func HandleMemberPhoneBind(ctx *gin.Context) {
	param := &request.BindPhoneInfoReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	log.Println("打印测试数据-更新用户信息", param)

	var phoneInfo = map[string]interface{}{}
	if param.EncryptedData == "" && param.Iv == "" {
		Response(ctx)("获取会员授权信息成功", CodeSuccess, phoneInfo)(OK)
		return
	}

	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	// 获取sessionKey
	rdbSessionKey := utils.Join(param.OpenId, "-sessionKey-secret")
	sessionKey := global.Rdb.Get(ctx, rdbSessionKey).Val()

	log.Println("打印测试session", param.OpenId, rdbSessionKey, sessionKey)

	// 解密微信数据
	str, err := wechatpay.Dncrypt(param.EncryptedData, sessionKey, param.Iv)

	if err != nil {
		Response(ctx)("解密失败", CodeError, err.Error())(Error)
		return
	}

	_ = json.Unmarshal([]byte(str), &phoneInfo)

	log.Println("解密后的用户信息", phoneInfo)

	waterMark := phoneInfo["watermark"].(map[string]interface{})
	logs.Info(phoneInfo["phoneNumber"].(string), userId, waterMark, waterMark["appid"].(string))
	//新增绑定日志
	m := &bindlogs.BindLogsModel{
		UserId:   userId,
		Phone:    phoneInfo["phoneNumber"].(string),
		Openid:   param.OpenId,
		Unionid:  param.Unionid,
		ClientIp: ctx.ClientIP(),
		CreateAt: dingo.Time(time.Now().Unix()),
		NickName: param.NickName,
		Appid:    waterMark["appid"].(string),
		BindDesc: "",
	}

	log.Println("绑定", m)
	// 更新绑定信息
	if param.OpenId != "" && phoneInfo["phoneNumber"].(string) != "" && param.Current == 2 {
		userModel := &users.UserModel{}
		userModel.Openid = param.OpenId
		userModel.Unionid = param.Unionid
		userModel.NickName = param.NickName
		userModel.ID = userId
		if ok := dao.NewUserDao().UpdateUserBindStatus(userModel).Unwrap().(bool); ok { // 绑定成功
			m.BindDesc = "绑定成功"
			dingo.Task(logic.NewLogsLogic().InsertBindLogs, func() {}, m)
			Response(ctx)("绑定成功", CodeSuccess, true)(OK)
			return
		}
	}
	m.BindDesc = "绑定失败"
	dingo.Task(logic.NewLogsLogic().InsertBindLogs, func() {}, m)
	Response(ctx)("绑定失败", CodeSuccess, false)(OK)

}

// HandleVerifyMemberPhoneBind 验证绑定手机是否一致
func HandleVerifyMemberPhoneBind(ctx *gin.Context) {
	param := &request.BindPhoneInfoReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	log.Println("打印测试数据-更新用户信息", param)

	var phoneInfo = map[string]interface{}{}
	if param.EncryptedData == "" && param.Iv == "" {
		Response(ctx)("获取会员授权信息成功", CodeSuccess, nil)(OK)
		return
	}

	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	// 获取sessionKey
	rdbSessionKey := utils.Join(param.OpenId, "-sessionKey-secret")
	sessionKey := global.Rdb.Get(ctx, rdbSessionKey).Val()

	log.Println("打印测试session", param.OpenId, rdbSessionKey, sessionKey)

	// 解密微信数据
	str, err := wechatpay.Dncrypt(param.EncryptedData, sessionKey, param.Iv)
	if err != nil {
		Response(ctx)("解密失败", CodeError, nil)(Error)
		return
	}

	_ = json.Unmarshal([]byte(str), &phoneInfo)
	log.Println("解密后的用户信息", str, phoneInfo)

	userInfo := dao.NewUserDao().GetUserInfoById(userId).Unwrap().(*users.UserModel)
	isVerifyPhone := userInfo.Phone == phoneInfo["phoneNumber"].(string)
	Response(ctx)("", CodeSuccess, isVerifyPhone)(OK)
}

// HandleVerifyAccountSmsCode 帐号短信验证
func HandleVerifyAccountSmsCode(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.StewardAppUserAccountLoginRes{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	userInfo := dao.NewUserDao().GetUserInfoById(userId).Unwrap().(*users.UserModel)
	checkInt := dao.NewUserDao().GetSmsCodeInfo(userInfo.Phone, param.Code).Unwrap().(int64)
	Response(ctx)("", CodeSuccess, checkInt > 0)(OK)
}

// HandleGetWxAuthHref 获取微信授权链接
func HandleGetWxAuthHref(ctx *gin.Context) {
	pathType := ctx.DefaultQuery("type", "1")
	redirectUri := global.Cfg.Wx.RedirectUri + "/user/auth"
	url := fmt.Sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?"+
		"appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s#wechat_redirect", global.Cfg.Wx.AppId, redirectUri, pathType)
	Response(ctx)("", CodeSuccess, url)(OK)
}

// HandleUserLogin 商户代理商登录
func HandleUserLoginByPlace(ctx *gin.Context) {
	log.Println("公众号登录")
	// 请求参数处理
	param := &struct {
		UserName string `json:"username"`
		UserPwd  string `json:"password"`
		Openid   string `json:"openid"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	log.Println("登录提交的参数", param)
	var loginInfo *request.LoginBack
	var err error

	//if param.Openid == "" {
	//	Response(ctx)("微信未授权，请刷新重试", CodeError, loginInfo)(OK)
	//	return
	//}

	loginInfo, err = logic.NewAuthLogic().
		UserLoginByPlace(param.UserName, param.UserPwd, param.Openid, ctx.ClientIP())
	if err != nil {
		//log.Println(err.Error())
		Response(ctx)(err.Error(), CodeSuccess, loginInfo)(OK)
		return
	}

	// 需要登录帐号密码，说明是第一次绑定，那么些微信下的所有订单恢复
	//dingo.Task(logic.NewAuthLogic().ResumeOrder, func() {}, param.UserName, param.Openid)

	// 响应请求
	Response(ctx)("登录成功", CodeSuccess, loginInfo)(OK)
}

// HandleUserSignLogin 签名登录
func HandleUserSignLogin(ctx *gin.Context) {
	log.Println("进入签约用户登录")
	// 请求参数处理
	param := &struct {
		UserName string `json:"username"`
		UserPwd  string `json:"password"`
		Openid   string `json:"openid"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	log.Println("签约用户登录提交的参数", param)
	var loginInfo *request.Sign
	var err error
	var customerId string

	//if param.Openid == "" {
	//	Response(ctx)("微信未授权，请刷新重试", CodeError, loginInfo)(OK)
	//	return
	//}

	loginInfo, err = logic.NewAuthLogic().
		UserSignLogin(param.UserName, param.UserPwd, param.Openid, ctx.ClientIP())
	if err != nil {
		//log.Println(err.Error())
		Response(ctx)(err.Error(), CodeSuccess, loginInfo)(OK)
		return
	}

	//userId, err := helper.GetUserIdFromCtx(ctx)
	//if err != nil {
	//	Response(ctx)(err.Error(), CodeSuccess, nil)(Unauthorized)
	//	return
	//}

	userInfo := memberdao.NewMemberDao().GetFddExtSignUserByOpenId(loginInfo.UserId).Unwrap().(users.UserModel)
	//有没有注册过
	fddExtSignUser, rowsAffected := memberdao.NewMemberDao().GetFddExtSignUserRows(userInfo.UserNo)
	//注册操作
	if rowsAffected <= 0 {
		fddExtSignUserModel := fddextsignuser.FddExtSignUser{}
		openId := userInfo.UserNo
		accountType := "1"

		//调用法大大注册接口
		resData := onlinesig.AccountRegister(openId, accountType)

		customerId = resData["data"].(string)

		//入库操作
		fddExtSignUserModel.UserId = userInfo.ID
		fddExtSignUserModel.CreateAt = dingo.Time(time.Now().Unix())
		fddExtSignUserModel.OpenId = openId
		fddExtSignUserModel.AccountType = accountType
		fddExtSignUserModel.IsExt = 1
		fddExtSignUserModel.CustomerId = resData["data"].(string) //注册成功返回的customer_id客户编号是用户在法大大的唯一标识。
		memberdao.NewMemberDao().InsertFddExtSignUser(&fddExtSignUserModel).Unwrap()

	}

	//返回地址
	var extUrl string

	FddExtSignUserInfo := fddExtSignUser.Unwrap().(fddextsignuser.FddExtSignUser)
	//未注册需要将客户ID绑定到model中
	if rowsAffected <= 0 {
		FddExtSignUserInfo.CustomerId = customerId
	}
	//是否实名认证过
	//请求法大大获取个人实名认证地址
	if FddExtSignUserInfo.IsExt < 2 {
		GetPersonVerifyUrlModel := request.GetPersonVerifyUrl{}
		verifyData := map[string]interface{}{}
		GetPersonVerifyUrlModel.CustomerId = FddExtSignUserInfo.CustomerId               //客户编号
		GetPersonVerifyUrlModel.VerifiedWay = "4"                                        //三要素
		GetPersonVerifyUrlModel.PageModify = "1"                                         //是否允许用户页面修改
		GetPersonVerifyUrlModel.NotifyUrl = global.Cfg.Fdd.FddNotifyUrl + "getVerifyNotify"     //回调地址
		GetPersonVerifyUrlModel.ReturnUrl = "http://webapp.chinaman.ink/user/signAffirm" //同步地址
		verifyData = onlinesig.GetPersonVerifyUrl(GetPersonVerifyUrlModel)
		data := verifyData["data"].(map[string]interface{})

		////解码
		decodeBytes, err := base64.StdEncoding.DecodeString(data["url"].(string))
		if err != nil {
			log.Fatalln(err)
		}
		extUrl = string(decodeBytes)
		fddExtSignUserModel := fddextsignuser.FddExtSignUser{}
		fddExtSignUserModel.UserId = userInfo.ID
		fddExtSignUserModel.TransactionNo = data["transactionNo"].(string)

		memberdao.NewMemberDao().UpdateFddUserTransactionNo(&fddExtSignUserModel)
	}
	loginInfo.ExtUrl = extUrl
	loginInfo.IsExt = strconv.Itoa(int(FddExtSignUserInfo.IsExt))
	// 响应请求
	Response(ctx)("登录成功", CodeSuccess, loginInfo)(OK)
}

func HandleUserLoginByAgent(ctx *gin.Context) {
	// 请求参数处理
	param := &struct {
		UserName string `json:"username"`
		Phone    string `json:"phone"`
		UserPwd  string `json:"password"`
		Passwd   string `json:"passwd"`
		IsPlace  int    `json:"isPlace"`
		Openid   string `json:"openid"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	var loginInfo *request.LoginBack
	var err error
	if param.IsPlace == 1 { // 商户登录
		loginInfo, err = logic.NewAuthLogic().
			UserLoginByPlace(param.UserName, param.UserPwd, param.Openid, ctx.ClientIP())
		if err != nil {
			//log.Println(err.Error())
			Response(ctx)(err.Error(), CodeSuccess, loginInfo)(OK)
			return
		}

		// 查询该微信是否有被 抽单的  订单，有则全部恢复  - 待开发

	} else { // 代理商登录
		Response(ctx)("代理商公众号平台还在开发中", CodeSuccess, &struct {
			Openid   string `json:"openid"`
			Token    string `json:"token"`
			UserName string `json:"user_name"`
			Avatar   string `json:"avatar"`
		}{Openid: "", Token: "", UserName: "", Avatar: ""})(OK)
		return
		// 登录业务逻辑处理
		//token, err = logic.NewAuthLogic().UserLoginByAgent(param.Phone, param.UserPwd, ctx.ClientIP())
		//if err != nil {
		//	Response(ctx)(err.Error(), CodeError, nil)(OK)
		//	return
		//}
	}

	// 响应请求
	Response(ctx)("登录成功", CodeSuccess, loginInfo)(OK)
}

// UserInfo 后台管理员信息
func HandleUserInfo(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}

	// 获取用户信息业务逻辑处理
	userInfo := logic.NewAuthLogic().GetUserInfo(userId)
	if userInfo.IsPlace == 1 {
		if logic.NewAuthLogic().GetCountChildrenById(userInfo.Id) > 0 {
			userInfo.IsPlace = 2
		}
	}

	log.Println("打印测试用户登录信息", userInfo)
	// 响应请求
	Response(ctx)("", CodeSuccess, userInfo)(OK)
}

// HandleUserAndParentInfo 后台管理员信息
func HandleUserAndParentInfo(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}

	// 获取用户信息业务逻辑处理
	userInfo := logic.NewAuthLogic().GetUserInfo(userId)
	if userInfo.IsPlace == 1 {
		if logic.NewAuthLogic().GetCountChildrenById(userInfo.Id) > 0 {
			userInfo.IsPlace = 2
		}
	}
	parentInfo := logic.NewAuthLogic().GetUserInfo(userInfo.ParentID)
	if parentInfo.IsAdmin == helper.TypeNumIsAdminResource {
		parentInfo.IsAdmin = helper.TypeNumIsAdminPartner
	}
	userInfo.ParentInfo = parentInfo

	log.Println("打印测试用户登录信息", userInfo)
	// 响应请求
	Response(ctx)("", CodeSuccess, userInfo)(OK)
}

// 微信公众号自动登录
func HandleWxUserInfo(ctx *gin.Context) {
	log.Println("微信自动登录")
	param := &struct {
		Code string `json:"code" binding:"required"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	token, openid, resp, err := logic.NewWxAuthLogic().VerifyWxUserInfo(param.Code, ctx.ClientIP())
	if err != nil {
		Response(ctx)(err.Error(), CodeError, nil)(OK)
		return
	}

	Response(ctx)("登录成功", CodeSuccess, &struct {
		Openid  string `json:"openid"`
		Token   string `json:"token"`
		Unionid string `json:"unionid"`
	}{Openid: openid, Token: token, Unionid: resp.Unionid})(OK)
}

// UserNav 后台管理员导航
func HandleUserNav(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err, userId).Unwrap()
	// 获取用户导航业务逻辑处理
	userNavList := logic.NewAuthLogic().GetUserNavList(userId)
	// 响应请求
	Response(ctx)("", CodeSuccess, userNavList)(OK)
}

// UserLogout 后台管理员退出
func HandleUserLogout(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}
	key := utils.Join("YdLogin-Token", strconv.Itoa(userId))
	// 清除redis缓存中的token
	global.Rdb.Del(ctx, key)
	Response(ctx)("成功退出", CodeSuccess, true)(OK)
}

// HandleUpdateUserLoginCount 更新用户登录次数
func HandleUpdateUserLoginCount(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	Response(ctx)("", CodeSuccess,
		dao.NewUserDao().UpdateUserLoginCount(userId).Unwrap())(OK)
}

//获取是否实名认证
func HandleGetExtSignInfo(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeSuccess, nil)(Unauthorized)
		return
	}
	//返回参数
	resParam := &struct {
		IsExt  string `json:"isExt"`
		ExtUrl string `json:"extUrl"`
	}{}
	//userId := 2
	fddExtSignUserInfo := memberdao.NewMemberDao().GetExtSignInfo(userId).Unwrap().(fddextsignuser.FddExtSignUser)
	//未实名
	if fddExtSignUserInfo.IsExt == 1 {
		GetPersonVerifyUrlModel := request.GetPersonVerifyUrl{}
		verifyData := map[string]interface{}{}
		GetPersonVerifyUrlModel.CustomerId = fddExtSignUserInfo.CustomerId               //客户编号
		GetPersonVerifyUrlModel.VerifiedWay = "4"                                        //三要素
		GetPersonVerifyUrlModel.PageModify = "1"                                         //是否允许用户页面修改
		GetPersonVerifyUrlModel.NotifyUrl = global.Cfg.Fdd.FddNotifyUrl + "getVerifyNotify"     //回调地址
		GetPersonVerifyUrlModel.ReturnUrl = "http://webapp.chinaman.ink/user/signAffirm" //同步地址
		verifyData = onlinesig.GetPersonVerifyUrl(GetPersonVerifyUrlModel)
		data := verifyData["data"].(map[string]interface{})

		////解码
		decodeBytes, err := base64.StdEncoding.DecodeString(data["url"].(string))
		if err != nil {
			log.Fatalln(err)
		}
		fddExtSignUserModel := fddextsignuser.FddExtSignUser{}
		fddExtSignUserModel.UserId = fddExtSignUserInfo.UserId
		fddExtSignUserModel.TransactionNo = data["transactionNo"].(string)

		resParam.IsExt = strconv.Itoa(int(fddExtSignUserInfo.IsExt))
		resParam.ExtUrl = string(decodeBytes)

		memberdao.NewMemberDao().UpdateFddUserTransactionNo(&fddExtSignUserModel)
		Response(c)("未实名认证", CodeSuccess, resParam)(OK)
		return
	}
	resParam.IsExt = strconv.Itoa(int(fddExtSignUserInfo.IsExt))

	Response(c)("已实名认证", CodeSuccess, resParam)(OK)
	return
}

//校验实名并且请求法大大实名证书申请
func HandleVerifyAndApplyCert(c *gin.Context) {
	param := &struct {
		AuthenticationType string `json:"authenticationType"`
		PersonName         string `json:"personName"`
		Sign               string `json:"sign"`
		Status             string `json:"status"`
		TransactionNo      string `json:"transactionNo"`
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()

	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeSuccess, nil)(Unauthorized)
		return
	}
	fddExtSignUserInfo := memberdao.NewMemberDao().GetExtSignInfo(userId).Unwrap().(fddextsignuser.FddExtSignUser)
	//查询用户信息
	//userInfo := dao.NewUserDao().GetUserInfoById(userId).Unwrap().(*users.UserModel)
	//Base64(SHA1(app_id + SHA1(app_secret+transactionNo+personName(companyName)+status+authenticationType)))
	////校验签名
	//shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.TransactionNo + param.PersonName + param.Status + param.AuthenticationType))
	//shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + shaStr1)
	//msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	//if param.Sign != msgDigest {
	//	Response(c)("实名认证失败", CodeSuccess, nil)(OK)
	//	return
	//}
	certInfo, err := onlinesig.GetFindPersonCertInfo(fddExtSignUserInfo.TransactionNo)
	if certInfo["status"].(string) != "2" || err != nil {
		Response(c)("实名认证失败", CodeSuccess, nil)(OK)
		return
	}

	//请求法大大实名证书申请
	data, err := onlinesig.GetVerifyApplyCert(fddExtSignUserInfo.CustomerId, fddExtSignUserInfo.TransactionNo)
	if err != nil {
		Response(c)("实名认证失败", CodeSuccess, err)(OK)
		return
	}
	if data["msg"] != "success" {
		Response(c)("实名认证失败", CodeSuccess, err)(OK)
		return
	}
	contractId := onlinesig.RandomStr(32)
	docTitle := global.Cfg.Fdd.FddDocTitle
	templateId := global.Cfg.Fdd.FddTemplateId
	//请求法大大合同上传
	generateContractModel := request.GenerateContractParam{}

	//乙方填充内容
	generateContractModel.UserName = certInfo["personName"].(string)
	//generateContractModel.UserPhone = userInfo.Phone
	generateContractModel.UserPhone = certInfo["mobile"].(string)
	generateContractModel.UsersInfo = certInfo["personName"].(string) + "/" + certInfo["mobile"].(string)
	//generateContractModel.UsersInfo = userInfo.UserName + "-" + userInfo.Phone
	generateContractModel.UserYear = time.Now().Format("2006")
	generateContractModel.UserMonth = time.Now().Format("01")
	generateContractModel.UserDay = time.Now().Format("02")
	generateContractModel.ContractId = contractId
	//generateContractModel.ProPortion = strconv.Itoa(userInfo.ProfitProportion)

	//甲方填充内容
	generateContractModel.Year = time.Now().Format("2006")
	generateContractModel.Month = time.Now().Format("01")
	generateContractModel.Day = time.Now().Format("02")
	err = onlinesig.GenerateContract(generateContractModel, contractId, docTitle, templateId)
	if err != nil {
		Response(c)("实名认证失败", CodeSuccess, err)(OK)
		return
	}
	//修改数据库中is_ext=2已实名
	fddExtSignUserModel := fddextsignuser.FddExtSignUser{}
	fddExtSignUserModel.UserId = userId
	fddExtSignUserModel.IsExt = 2
	fddExtSignUserModel.ContractId = contractId
	memberdao.NewMemberDao().UpdateFddUserIsExt(&fddExtSignUserModel).Unwrap()

	Response(c)("实名认证成功", CodeSuccess, true)(OK)
}

func Test(c *gin.Context) {
	//fddExtSignUserInfo := memberdao.NewMemberDao().GetExtSignInfo(666).Unwrap().(fddextsignuser.FddExtSignUser)
	userInfo := dao.NewUserDao().GetUserInfoById(139).Unwrap().(*users.UserModel)
	contractId := onlinesig.RandomStr(32)
	docTitle := global.Cfg.Fdd.FddDocTitle
	templateId := "2021062118"
	//请求法大大合同上传
	generateContractModel := request.GenerateContractParam{}

	//乙方填充内容
	generateContractModel.UserName = userInfo.UserName
	generateContractModel.UserPhone = userInfo.Phone
	generateContractModel.UsersInfo = userInfo.UserName + "-" + userInfo.Phone
	generateContractModel.UserYear = time.Now().Format("2006")
	generateContractModel.UserMonth = time.Now().Format("01")
	generateContractModel.UserDay = time.Now().Format("02")
	generateContractModel.ContractId = contractId

	//甲方填充内容
	generateContractModel.Year = time.Now().Format("2006")
	generateContractModel.Month = time.Now().Format("01")
	generateContractModel.Day = time.Now().Format("02")

	err := onlinesig.GenerateContract(generateContractModel, contractId, docTitle, templateId)
	if err != nil {
		Response(c)("实名认证失败", CodeSuccess, err)(OK)
		return
	}
	fddExtSignUserModel := fddextsignuser.FddExtSignUser{}
	fddExtSignUserModel.UserId = 666
	fddExtSignUserModel.ContractId = contractId
	fddExtSignUserModel.DocTitle = docTitle
	memberdao.NewMemberDao().UpdateFddUserIsExt(&fddExtSignUserModel).Unwrap()
}
